package com.kaiyidiannao.activity.daydaycoupon;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;
import com.kaiyidiannao.adapter.DaydaycouponShoppingCarAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.util.ArithUtils;
import com.kaiyidiannao.common.util.DisplayUtil;
import com.kaiyidiannao.common.util.MySystemParams;
import com.kaiyidiannao.common.util.UIUitls;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.DaydayCouponBean;
import com.kaiyidiannao.model.bean.ShoppingCarBean;
import com.kaiyidiannao.model.req.model.PostShoppingCarClear;
import com.kaiyidiannao.model.req.model.PostShoppingCarLIst;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.MyDialogWaitingAndDel;
import com.kaiyidiannao.view.QuantitySelectorView;

import java.util.*;
import java.util.logging.Handler;

/**
 * Created by david on 14-4-15.
 * 天天惠 - 购物车
 */
public class DdcShoppingCarActivity extends BaseActionBarActivity implements Observer, MyDialogWaitingAndDel.IDialogOnclickInterface {

    private static final String TAG = "DdcShoppingCarActivity";

    private TextView mPriceTv;//总价格
    private BaseAdapter adapter;
    private ListView listView;
    private ArrayList<DaydayCouponBean> targetList = DataCenter.shoppingCarList;
    private int longClickPosition;
    private MyDialogWaitingAndDel myDialog;
    private View currentItemView;
    private ImageView payImageVIew;

    private String itemid; //商品id
    private String currentKey = ""; //当前被点击的item编号对应商品的key
    private boolean isFisrt = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.daydaycoupon_shoppongcar_xml);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        DataCenter.shoppingCarMap.clear();


        //处理ActionBar
        findActionBar();
        findViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFisrt) {
            isFisrt = false;
        } else {
            showProgressDialog();
            if (isLogin()) {
                new PostShoppingCarLIst(DataCenter.userLogin.get(0).getUserid()).execute();
            }
        }

    }


    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("购物车");
    }

    private void findViews() {

        showProgressDialog();
        if (isLogin()) {
            new PostShoppingCarLIst(DataCenter.userLogin.get(0).getUserid()).execute();
        }

        myDialog = new MyDialogWaitingAndDel(this, R.style.MyDialogStyle);
        mPriceTv = (TextView) findViewById(R.id.daydaycoupon_price_count);
        Log.d(TAG, "mPriceTv.getText()|" + mPriceTv.getText() + "|");

        adapter = new DaydaycouponShoppingCarAdapter(this, targetList);

        listView = (ListView) findViewById(R.id.daydaycoupon_shopping_car_listview);
        listView.setAdapter(adapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {


                int[] location = new int[2];
                // 获取当前view在屏幕中的绝对位置
                // ,location[0]表示view的x坐标值,location[1]表示view的坐标值
                view.getLocationOnScreen(location);
                view.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
                currentItemView = view;
                longClickPosition = position;
                DisplayMetrics displayMetrics = new DisplayMetrics();
                Display display = DdcShoppingCarActivity.this.getWindowManager().getDefaultDisplay();
                display.getMetrics(displayMetrics);
                WindowManager.LayoutParams params = myDialog.getWindow().getAttributes();
                params.gravity = Gravity.BOTTOM;

                float scale = MySystemParams.getInstance(DdcShoppingCarActivity.this).scale;
                params.y = display.getHeight() - location[1] - DisplayUtil.px2dip(20, scale);
                myDialog.getWindow().setAttributes(params);
                myDialog.setCanceledOnTouchOutside(true);
                myDialog.show();

                itemid = targetList.get(position).getItemid();
                return false;
            }
        });
        myDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));
            }
        });

        payImageVIew = (ImageView) findViewById(R.id.daydaycoupon_alipay);
        payImageVIew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 先进行有效性判断
                if (shopingCarIsSelected()) {
                    Intent intent = new Intent(DdcShoppingCarActivity.this, DdcPayActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("money",  mPriceTv.getText() + ""); //商品总价格

                    // 传递购物车参数
                    // 参数一：购物车商品参数
                    ShoppingCarBean shoppingCarBean = new ShoppingCarBean();
                    Map<String, String> specMap = getSpeceData();
                    shoppingCarBean.setKeyNumbers(specMap);
                    intent.putExtra("KeyNumbers", shoppingCarBean);
                    // 参数二：购物车标题
                    intent.putExtra("subject", getProdectTitles());
                    // 参数三：第一件商品的运费
                    intent.putExtra("fare", getFare());
                    // 参数四：第一件商品的支付方式
                    intent.putExtra("paymethods", getPayMethods());
                    // 参数五：获取单件商品的最高运费
                    intent.putExtra("maxFare", getMaxFare());
                    // 参数五：选择支付方式为"货到付款"时，运费按照单价商品累加
                    intent.putExtra("allFare", getAllFare());

                    Log.d(TAG, "getFare:" + getFare());
                    Log.d(TAG, "getPayMethods:" +  getPayMethods());
                    Log.d(TAG, "getAllFare:" +  getAllFare());
                    Log.d(TAG, "getMaxFare:" +  getMaxFare());

                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    showToast("请先挑选一件商品吧！！");
                }
            }
        });
    }

    /**
     * 获取第一件商品的运费
     * @return
     */
    private String getFare() {

       String fareStr = "";
//        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView fareTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_fare);

                if (toggleButton.isChecked()) {
                    fareStr = fareTextView.getText().toString();
                    Log.d(TAG, "[getFare]:" + fareStr);
                }

            }
        }
        return fareStr;

    }


    /**
     * 选择支付方式为"货到付款"时，运费按照单价商品累加
     * @return
     */
    private String getAllFare() {

        double fare = 0;
        //        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView fareTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_fare);

                if (toggleButton.isChecked()) {
                    String fareStr = fareTextView.getText().toString();
                    fare = ArithUtils.add(fare, Double.parseDouble(fareStr));
                    Log.d(TAG, "[getAllFare --- ]:" + fare);
                }

            }
        }
        return fare + "";

    }

    /**
     * 获取单件商品的最高运费
     * @return
     */
    private String getMaxFare() {


        double maxFare = 0; //最高运费
//        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView fareTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_fare);

                if (toggleButton.isChecked()) {
                    String fareStr = "";
                    fareStr = fareTextView.getText().toString();
                    if (Double.parseDouble(fareStr) > maxFare) {
                        maxFare = Double.parseDouble(fareStr);
                    }
                }

            }
        }
        return maxFare + "";

    }

    /**
     * 获取第一件商品的支付方式
     */
    private String getPayMethods() {
        String paymthodStr = "";
//        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView paymthodsTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_paymethods);

                if (toggleButton.isChecked()) {
                    paymthodStr = paymthodsTextView.getText().toString();
                    break;
                }

            }
        }
        return paymthodStr;
    }


    private boolean shopingCarIsSelected() {
        //        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                if (toggleButton.isChecked()) {
                    return true;
                }

            }
        }
        return false;
    }

    /**
     * 获取规格参数
     *
     * @return
     */
    private Map<String, String> getSpeceData() {
        TreeMap<String, String> specMap = new TreeMap<String, String>();

        //        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView keyTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_car_key);
                QuantitySelectorView quantitySelectorView = (QuantitySelectorView) view.findViewById(R.id.daydaycoupon_shopping_car_num);

                if (toggleButton.isChecked()) {
                    String key = keyTextView.getText().toString();
                    int value = quantitySelectorView.getCount();
                    specMap.put(key, value + "");
                }

            }
        }
        return specMap;
    }

    /**
     * 获取商品标题
     *
     * @return
     */
    private String getProdectTitles() {

        String subject = "";

        //        for (int i = 0; i < listView.getCount(); ++i) {
        for (Map.Entry<Integer, View> entry : DataCenter.shoppingCarMap.entrySet()) {
//            View view = listView.getChildAt(i);
            View view = entry.getValue();
            if (view != null) {

                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.daydaycoupon_shopping_car_toggle_button);
                TextView titleTextView = (TextView) view.findViewById(R.id.daydaycoupon_shopping_car_product_name);

                if (toggleButton.isChecked()) {
                    String title = titleTextView.getText().toString();
                    subject = (subject.equals("")) ? "" : (subject + ";");
                    subject += title;
                }

            }
        }
        return subject;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        DataCenter.shoppingCarList.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        closeProgressDialog();

        if (flag == DataCenter.flag.SHOPPING_CAR_RESULT_DATA_SUCCESS) { //购物车列表获取成功
            if (targetList != null && targetList.size() >= 1) {
                this.showShoppingCarList();
            } else {
                this.showEmptyDataView();
            }
        } else if (flag == DataCenter.flag.SHOPPING_CAR_RESULT_DATA_FAILED) {
              this.showReloadView();
        }

        if (flag == DataCenter.flag.SHOPPING_CAR_DEL_SUCESS) { //删除购物车成功
            targetList.remove(longClickPosition); //删除数据
            adapter.notifyDataSetChanged();
            showToast("删除成功！");
            DataCenter.shoppingCarMap.remove(longClickPosition);

            if (targetList.size() <= 0) {
                this.showEmptyDataView();
            } else {
                this.showShoppingCarList();
            }
        } else if (flag == DataCenter.flag.SHOPPING_CAR_DEL_FAILED) {//删除购物车失败
            showToast("删除失败重试，请重试！");
        }

    }

    private void showShoppingCarList() {
        findViewById(R.id.daydaycoupon_shoopingcar_framelayout).setVisibility(View.VISIBLE);
        findViewById(R.id.realod_layout).setVisibility(View.GONE);
        findViewById(R.id.daydaycoupon_shopping_car_listview_father).setVisibility(View.VISIBLE);
        findViewById(R.id.shopping_car_layout_empty).setVisibility(View.GONE);
        this.refreshShoppingCar();
    }

    private void showEmptyDataView() {
        findViewById(R.id.daydaycoupon_shoopingcar_framelayout).setVisibility(View.VISIBLE);
        findViewById(R.id.realod_layout).setVisibility(View.GONE);
        findViewById(R.id.daydaycoupon_shopping_car_listview_father).setVisibility(View.GONE);
        findViewById(R.id.shopping_car_layout_empty).setVisibility(View.VISIBLE);
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.daydaycoupon_shoopingcar_framelayout).setVisibility(View.VISIBLE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.daydaycoupon_shopping_car_listview_father).setVisibility(View.GONE);
        findViewById(R.id.shopping_car_layout_empty).setVisibility(View.GONE);

        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog();

                findViewById(R.id.daydaycoupon_shoopingcar_framelayout).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
                findViewById(R.id.daydaycoupon_shopping_car_listview_father).setVisibility(View.GONE);
                findViewById(R.id.shopping_car_layout_empty).setVisibility(View.GONE);

                if (isLogin()) {
                    new PostShoppingCarLIst(DataCenter.userLogin.get(0).getUserid()).execute();
                }
            }
        });
    }

    /**
     * 刷新购物车
     */
    private void refreshShoppingCar() {
        adapter.notifyDataSetChanged();
        float density = getResources().getDisplayMetrics().density; // 屏幕密度（0.75 / 1.0 / 1.5）
        UIUitls.setListViewHeightBasedOnChildren(listView, (int) (density * 20));
        android.os.Handler handler = new android.os.Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                // 获取总价格
                String countMoneyStr = ((DaydaycouponShoppingCarAdapter)adapter).countSumMoney(DdcShoppingCarActivity.this, true);
                Log.d(TAG, "mPriceTv.getText()|!!!!" +countMoneyStr + "－－－－" + mPriceTv.getText() + "|");
                mPriceTv.setText(countMoneyStr);
                Log.d(TAG, "mPriceTv.getText()|" +countMoneyStr + "－－－－" + mPriceTv.getText() + "|");
            }
        });
    }

    @Override
    public void leftOnclick() {//代办
        myDialog.dismiss();
        currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));
        //targetList.remove(longClickPosition);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void rightOnclick() {//删除
        myDialog.dismiss();
        currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));

        showProgressDialog();

        // 根据postion获取当前被点击商品的key
        View curView = listView.getChildAt(longClickPosition);
        if (curView != null) {
            TextView keyTextView = (TextView) curView.findViewById(R.id.daydaycoupon_shopping_car_key);
            currentKey = keyTextView.getText().toString();
        }

        // 根据postion获取当前被点击商品的key
        if (!TextUtils.isEmpty(currentKey)) {
            new PostShoppingCarClear(currentKey, getUserid()).execute();
        }
    }

}
